<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\controller\api\store;


use app\Request;
use app\services\order\OtherOrderServices;
use app\services\order\store\BranchOrderServices;
use app\services\order\StoreOrderServices;
use app\services\store\SystemStoreServices;
use app\services\store\SystemStoreStaffServices;
use app\services\system\attachment\SystemAttachmentServices;
use app\services\user\UserCardServices;
use app\services\user\UserRechargeServices;
use app\services\user\UserServices;
use app\services\user\UserSpreadServices;
use app\services\wechat\WechatCardServices;
use crmeb\services\CacheService;
use crmeb\services\UploadService;
use crmeb\services\UtilService;
use crmeb\services\wechat\MiniProgram;
use crmeb\services\wechat\OfficialAccount;
use GuzzleHttp\Psr7\Utils;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\Response;


/**
 * 店员
 * Class StoreStaff
 * @package app\controller\api\store
 */
class StoreStaff
{
    /**
     * @var SystemStoreStaffServices
     */
    protected $services;

    /**
     * @var int
     */
    protected $uid;
    /**
     * 门店店员信息
     * @var array
     */
    protected $staffInfo;
    /**
     * 门店id
     * @var int|mixed
     */
    protected $store_id;

    /**
     * 门店店员ID
     * @var int|mixed
     */
    protected $staff_id;

    /**
     * 构造方法
     * StoreStaff constructor.
     * @param SystemStoreStaffServices $services
     */
    public function __construct(SystemStoreStaffServices $services, Request $request)
    {
        $this->services = $services;
        $this->uid = (int)$request->uid();
        $this->staffInfo = $services->getStaffInfoByUid($this->uid)->toArray();
        $this->store_id = (int)$this->staffInfo['store_id'] ?? 0;
        $this->staff_id = (int)$this->staffInfo['id'] ?? 0;
    }

    /**
     * 获取店员信息
     * @return mixed
     */
    public function info(SystemStoreServices $storeServices)
    {
		$staffInfo = $this->staffInfo;
		$staffInfo['store_info'] = $storeServices->getOne(['id' => $this->store_id], 'product_category_status,name');
		$data = $storeServices->getStoreQrcode((int)$this->store_id, (int)$this->staff_id);
		$staffInfo = array_merge($staffInfo, $data);
        return app('json')->success($staffInfo);
    }

    /**
     * 工作台数据
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function stagingData(Request $request)
    {
        [$is_manager, $time] = $request->getMore([
            ['is_manager', 0],
            ['data', '', '', 'time'],
        ], true);
        if (!$is_manager || !$this->staffInfo['is_manager']) {
            $is_manager = 0;
        }
        $store_id = $this->store_id;
        $staff_id = $is_manager ? 0 : $this->staff_id;
        return app('json')->successful($this->services->getStagingData($store_id, $staff_id));
    }


    /**
     * 店员｜门店数据统计
     * @param Request $request
     * @return mixed
     */
    public function statistics(Request $request)
    {
        [$is_manager, $time] = $request->getMore([
            ['is_manager', 0],
            ['data', '', '', 'time'],
        ], true);
        if (!$is_manager || !$this->staffInfo['is_manager']) {
            $is_manager = 0;
        }
        $store_id = $this->store_id;
        $staff_id = $is_manager ? 0 : $this->staff_id;
        $data = $this->services->getStoreData($this->uid, $store_id, $staff_id, $time);
        return app('json')->successful($data);
    }

    /**
     * 统计图表
     * @param Request $request
     * @param $type
     * @return Response
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function timeChart(Request $request, $type = 1)
    {
        [$is_manager, $time] = $request->getMore([
            ['is_manager', 0],
            ['time', 'today'],
        ], true);
        [$start, $end, $timeType, $timeKey] = $this->services->timeHandle($time, true);
        if (!$is_manager || !$this->staffInfo['is_manager']) {
            $is_manager = 0;
        }
        $staff_id = (int)($is_manager ? 0 : $this->staff_id);
        $store_id = (int)$this->store_id;
        switch ($type) {
            case 1://销售额
            case 2://配送订单金额
            case 3://配送订单数量
            case 4://退款订单金额
            case 5://收银订单金额
            case 6://核销订单金额
                /** @var BranchOrderServices $order */
                $order = app()->make(BranchOrderServices::class);
                $list = $order->time($store_id, $staff_id, $type, [$start, $end], $timeType);
                break;
            case 7://付费会员
                /** @var OtherOrderServices $otherOrder */
                $otherOrder = app()->make(OtherOrderServices::class);
                $list = $otherOrder->time($store_id, $staff_id, [$start, $end], $timeType);
                break;
            case 8://充值
                /** @var UserRechargeServices $userRecharge */
                $userRecharge = app()->make(UserRechargeServices::class);
                $list = $userRecharge->time($store_id, $staff_id, [$start, $end], $timeType);
                break;
            case 9://推广用户
                /** @var UserSpreadServices $userSpread */
                $userSpread = app()->make(UserSpreadServices::class);
                $list = $userSpread->time($this->store_id, $staff_id, [$start, $end], $timeType);
                break;
            case 10://激活会员卡
                /** @var UserCardServices $userCard */
                $userCard = app()->make(UserCardServices::class);
                $list = $userCard->time($this->store_id, $staff_id, [$start, $end], $timeType);
                break;
            default:
                return app('json')->fail('没有此类型');
        }
        $result = [];
        if ($list) {
            $list = array_combine(array_column($list, 'day'), $list);
        }
        foreach ($timeKey as $value) {
            $key = in_array($type, [3, 9, 10]) ? 'count' : 'price';
            $result[] = ['time' => $time == 'month' ? date('d', strtotime($value)) : $value, 'number' => $list[$value][$key] ?? 0, 'price' => in_array($type, [3, 9, 10]) ? 0 : $list[$value]['price'] ?? 0, 'num' => $list[$value]['count'] ?? 0];
        }
        return app('json')->successful($result);
    }


    /**
     * 店员｜门店统计详情页列表
     * @param Request $request
     * @param $type
     * @return Response
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function data(Request $request, $type)
    {
        [$is_manager, $time] = $request->getMore([
            ['is_manager', 0],
            ['time', 'today'],
        ], true);
        [$start, $end, $timeType, $timeKey] = $time = $this->services->timeHandle($time, true);
        if (!$is_manager || !$this->staffInfo['is_manager']) {
            $is_manager = 0;
        }
        $staff_id = (int)($is_manager ? 0 : $this->staff_id);
        $store_id = (int)$this->store_id;
        $timeType = 'day';
        switch ($type) {
            case 1://销售额
            case 2://配送订单金额
            case 3://配送订单数量
            case 4://退款订单金额
            case 5://收银订单金额
            case 6://核销订单金额
                /** @var BranchOrderServices $order */
                $order = app()->make(BranchOrderServices::class);
                $list = $order->time($store_id, $staff_id, $type, [$start, $end], $timeType);
                break;
            case 7://付费会员
                /** @var OtherOrderServices $otherOrder */
                $otherOrder = app()->make(OtherOrderServices::class);
                $list = $otherOrder->time($store_id, $staff_id, [$start, $end], $timeType);
                break;
            case 8://充值
                /** @var UserRechargeServices $userRecharge */
                $userRecharge = app()->make(UserRechargeServices::class);
                $list = $userRecharge->time($this->store_id, $staff_id, [$start, $end], $timeType);
                break;
            case 9://推广用户
                /** @var UserSpreadServices $userSpread */
                $userSpread = app()->make(UserSpreadServices::class);
                $list = $userSpread->time($this->store_id, $staff_id, [$start, $end], $timeType);
                break;
            case 10://激活会员卡
                /** @var UserCardServices $userCard */
                $userCard = app()->make(UserCardServices::class);
                $list = $userCard->time($this->store_id, $staff_id, [$start, $end], $timeType);
                break;
            default:
                return app('json')->fail('没有此类型');
        }
        return app('json')->success($list);
    }


    /**
     * 商品分享二维码 推广员
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function code(Request $request, WechatCardServices $cardServices)
    {
        $wechatCard = $cardServices->get(['card_type' => 'member_card', 'status' => 1, 'is_del' => 0]);
        $uid = (int)$request->uid();
        if ($wechatCard && !$request->isApp()) {

            $key = $wechatCard['card_id'] . '_cart_' . $uid;
            $data = CacheService::get($key);
            if (!$data) {
                $result = OfficialAccount::getCardQRCode($wechatCard['card_id'], $uid);
                $data = [
                    'url' => $result['url'] ?? '',
                    'show_qrcode_url' => $result['show_qrcode_url'] ?? ''
                ];
                CacheService::set($key, $data, 1500);
            }
        } else {
            $site_url = sys_config('site_url');
            $valueData = 'spread=' . $uid . '&spid=' . $uid;
            $url = $site_url ? $site_url . '?' . $valueData : '';
            if (request()->isRoutine()) {
                try {
                    //小程序
                    $name = $uid . '_store_share_routine.jpg';
                    /** @var SystemAttachmentServices $systemAttachmentServices */
                    $systemAttachmentServices = app()->make(SystemAttachmentServices::class);
                    $imageInfo = $systemAttachmentServices->getInfo(['name' => $name]);
                    if (!$imageInfo) {
                        $res = MiniProgram::appCodeUnlimit($valueData, 'pages/index/index', 280);
                        if (!$res) throw new ValidateException('二维码生成失败');
                        $uploadType = (int)sys_config('upload_type', 1);
                        $upload = UploadService::init($uploadType);
                        $res = (string)Utils::streamFor($res);
                        $res = $upload->to('routine/store/code')->validate()->stream($res, $name);
                        if ($res === false) {
                            throw new ValidateException($upload->getError());
                        }
                        $imageInfo = $upload->getUploadInfo();
                        $imageInfo['image_type'] = $uploadType;
                        if ($imageInfo['image_type'] == 1) $remoteImage = UtilService::remoteImage($site_url . $imageInfo['dir']);
                        else $remoteImage = UtilService::remoteImage($imageInfo['dir']);
                        if (!$remoteImage['status']) throw new ValidateException($remoteImage['msg']);
                        $systemAttachmentServices->save([
                            'name' => $imageInfo['name'],
                            'att_dir' => $imageInfo['dir'],
                            'satt_dir' => $imageInfo['thumb_path'],
                            'att_size' => $imageInfo['size'],
                            'att_type' => $imageInfo['type'],
                            'image_type' => $imageInfo['image_type'],
                            'module_type' => 2,
                            'time' => time(),
                            'pid' => 1,
                            'type' => 1
                        ]);
                        $url = $imageInfo['dir'];
                    } else {
                        $url = $imageInfo['att_dir'];
                    }
                    if ($imageInfo['image_type'] == 1)
                        $url = $site_url . $url;
                } catch (\Throwable $e) {
                }
            }
            $data = [
                'url' => $url,
                'show_qrcode_url' => $url
            ];
        }
        return app('json')->success($data);
    }

}
